package com.guigu.work.controller;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.guigu.tms.exception.TmsException;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import com.guigu.work.dto.DriverJobDTO;
import com.guigu.work.entity.DriverJob;
import com.guigu.work.entity.TaskTransport;
import com.guigu.work.entity.TransportOrder;
import com.guigu.work.entity.TransportOrderTask;
import com.guigu.work.feign.BaseFeign;
import com.guigu.work.feign.OrderFeign;
import com.guigu.work.service.DriverJobService;
import com.guigu.work.service.TaskTransportService;
import com.guigu.work.service.TransportOrderService;
import com.guigu.work.service.TransportOrderTaskService;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 司机作业单 前端控制器
 * </p>
 *
 * @author liAo
 * @since 2021-11-09
 */
@Api(tags = "司机作业单操作接口")
@RestController
@RequestMapping("/driver-job")
public class DriverJobController {
    @Autowired
    private DriverJobService service;

    @Autowired
    private BaseFeign baseFeign;

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private TaskTransportService taskTransportService;

    @Autowired
    private TransportOrderTaskService transportOrderTaskService;

    @Autowired
    private TransportOrderService transportOrderService;

    /**
     * 新增司机作业单
     *
     * @param dto 司机作业单信息
     * @return 司机作业单信息
     */
    @ApiOperation("新增司机作业单")
    @PostMapping("/save")
    public R save(@RequestBody DriverJobDTO dto) {

        /**
         * 新增作业单
         */
        DriverJob driverJob = service.saveDriverJob(dto);
        return new R(ResultCode.SUCCESS_CODE, "新增司机作业单成功!", driverJob);
    }

    /**
     * 修改司机作业单
     *
     * @param dto 司机作业单信息
     * @return 司机作业单信息
     */
    @ApiOperation("修改司机作业单")
    @PostMapping("/update")
    public R update(@RequestBody DriverJobDTO dto) {
        DriverJob driverJob = service.updateDriverJob(dto);
        return new R(ResultCode.SUCCESS_CODE, "修改司机作业单成功!", driverJob);
    }

    /**
     * 获取司机作业单分页数据
     *
     * @param dto 司机作业单信息
     * @return 司机作业单信息
     */
    @ApiOperation(value = "获取司机作业单分页数据", notes = "必须:page-pageSize|可选:id-status-taskTransportId-driverId")
    @PostMapping("/page")
    public R page(@RequestBody DriverJobDTO dto) {
        IPage<DriverJob> jobIPage = null;
        if (null != dto) {

            jobIPage = service.findByPage(dto);
        }
        return new R(ResultCode.SUCCESS_CODE, "获取司机作业单分页数据成功!", jobIPage);
    }

    /**
     * 根据司机id获取司机作业单信息
     *
     * @param driverId 司机id
     * @return 司机作业单信息
     */

    @ApiOperation(value = "根据司机id获取司机作业单信息")
    @GetMapping("/{driverId}")
    public R findById(@PathVariable(name = "driverId") String driverId) {
        if (StringUtils.isBlank(driverId)) {
            throw new IllegalArgumentException("参数异常!");
        }
        Map<String, Object> map = new HashMap<>();
        ArrayList l1 = new ArrayList();
        ArrayList l2 = new ArrayList();
        ArrayList l3 = new ArrayList();
        List<DriverJob> list = service.list(new QueryWrapper<DriverJob>().eq("driver_id", driverId));
        if (CollUtil.isNotEmpty(list)) {
            for (DriverJob dj : list) {
                Map<String, Object> m1 = new HashMap<>();
                //起始目的网点信息
                R<Map> mapR = baseFeign.driverInfo(dj.getStartAgencyId(), dj.getEndAgencyId());
                m1.put("agency", mapR.getData());
                //运输任务
                  TaskTransport task = taskTransportService.getById(dj.getTaskTransportId());
                m1.put("task", task);
                if (dj.getStatus() == 1) {
                    m1.put("driverJob", dj);
                    l1.add(m1);
                } else if (dj.getStatus() == 2) {
                    m1.put("driverJob", dj);
                    l2.add(m1);
                } else {
                    m1.put("driverJob", dj);
                    l3.add(m1);
                }

            }
        }
        map.put("l1", l1);
        map.put("l2", l2);
        map.put("l3", l3);
        return new R(ResultCode.SUCCESS_CODE, "根据司机id获取司机作业单信息成功!", map);
    }

    /**
     * 多条件查询司机作业单
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "多条件查询司机作业单", notes = "ids-id-status-driverId-taskTransportId")
    @PostMapping("/findAll")
    public R findAll(@RequestBody DriverJobDTO dto) {

        List<DriverJobDTO> driverJobs = service.findAll(dto);

        return new R(ResultCode.SUCCESS_CODE, "多条件查询司机作业单成功!", driverJobs);
    }

    /**
     * 司机作业单提货
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "司机作业单提货", notes = "提货对接人-凭证照片-货物照片")
    @PostMapping("/tiHuo")
    public R tiHuo(@RequestBody Map map) {
        if(CollUtil.isEmpty(map)){
            throw new IllegalArgumentException("参数异常!");
        }
        String id= (String) map.get("id");
        //获取job
        DriverJob driverJob = service.getById(id);
        //actual_departure_time 实际发车时间
        driverJob.setActualDepartureTime(new Date());
        //提货对接人
        driverJob.setStartHandover((String) map.get("startHandover"));
        //状态
        driverJob.setStatus(2);
        boolean b = service.updateById(driverJob);
        TaskTransport transport = taskTransportService.getById(driverJob.getTaskTransportId());
        //TODO 运输任务修改
        //status
        transport.setStatus(2);
        //actual_departure_time 实际发车时间
        transport.setActualDepartureTime(new Date());
        //凭证 cargo_pick_up_picture
        transport.setCargoPickUpPicture((String) map.get("cargoPickUpPicture"));
        //货物照片
        transport.setCargoPicture((String) map.get("cargoPicture"));
        //提货经纬度
        transport.setDeliveryLongitude((String) map.get("lo"));
        transport.setDeliveryLongitude((String) map.get("la"));
        b=taskTransportService.updateById(transport);

        //所有相关订单状态修改
        List<TransportOrderTask> tots = transportOrderTaskService.findAll(null, transport.getId());
        List<String> transportOrderIds = new ArrayList<>();

        if(CollUtil.isNotEmpty(tots)){
            transportOrderIds=tots.stream().map(TransportOrderTask::getTransportOrderId).collect(Collectors.toList());
        }
        Collection<TransportOrder> transportOrders = transportOrderService.listByIds(transportOrderIds);
        for (TransportOrder to: transportOrders){
            //在途
            orderFeign.updateStatusById(to.getOrderId(), 5);
        }
        return new R(ResultCode.SUCCESS_CODE, "提货成功!!", b);
    }

    /**
     * 司机作业单交付
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "司机作业单交付", notes = "交付对接人-运回单凭证-交付货物照片")
    @PostMapping("/jiaoFu")
    public R jiaoFu(@RequestBody Map map) {
        if(CollUtil.isEmpty(map)){
            throw new IllegalArgumentException("参数异常!");
        }
        String id= (String) map.get("id");
        //获取job
        DriverJob driverJob = service.getById(id);
        //actual_arrival_time 实际到达时间
        driverJob.setActualArrivalTime(new Date());
        //交付对接人
        driverJob.setFinishHandover((String) map.get("finishHandover"));
        //状态
        driverJob.setStatus(4);
        boolean b = service.updateById(driverJob);
        TaskTransport transport = taskTransportService.getById(driverJob.getTaskTransportId());
        //TODO 运输任务修改
        //status
        transport.setStatus(4);
        //actual_arrival_time 实际到达时间
        transport.setActualArrivalTime(new Date());
        //运输回执单 transportCertificate
        transport.setTransportCertificate((String) map.get("transportCertificate"));
        //交付货物照片 deliverPicture
        transport.setDeliverPicture((String) map.get("deliverPicture"));
        //交付经纬度
        transport.setDeliverLongitude((String) map.get("lo"));
        transport.setDeliverLongitude((String) map.get("la"));
        b=taskTransportService.updateById(transport);

        //所有相关订单状态修改 运单状态修改
        List<TransportOrderTask> tots = transportOrderTaskService.findAll(null, transport.getId());
        List<String> transportOrderIds = new ArrayList<>();

        if(CollUtil.isNotEmpty(tots)){
            transportOrderIds=tots.stream().map(TransportOrderTask::getTransportOrderId).collect(Collectors.toList());
        }
        Collection<TransportOrder> transportOrders = transportOrderService.listByIds(transportOrderIds);
        for (TransportOrder to: transportOrders){

            //网点出库，待派送
            orderFeign.updateStatusById(to.getOrderId(), 6);
        }
        return new R(ResultCode.SUCCESS_CODE, "交付成功!!", b);
    }
}

